<template>
  <nly-content-wrapper class="report-form">
    <div class="a-base-container">
      <div class="view">
        <div class="wh100 resize-table-container">
          <a-tabs class="wh100" v-model="tabKey" :animated="false" @change="tabChange">
            <a-tab-pane key="1" tab="客户跟进分析">
              <div class="a-button-bar">
                <nly-row class="col-12 ml-1 mb-2 lr mt-4">
                  <nly-col xs="12" sm="12" md="12" lg="12" xl="12" class="form-inline" style="justify-content: left;">
                    <form-select title="客户类型"  class="ml-2" rightStyle="width:120px;" v-model="postData.crmType"  addDefaultText="全部"
                      :dataList="[
                      { key: 0, title: '线索客户' },
                      { key: 1, title: '潜在客户' },
                      { key: 2, title: '成交客户' }]"/>
                    <form-rang-date-picker title="联系时间" size="small" rightStyle="min-width: 150px; max-width: calc(410px + 0.25rem);" format="YYYY-MM-DD" v-model="touchDate"/>
                    <form-input title="客户名称" placeholder="全部" id="crmName" labelStyle rightStyle="width:120px;" class="ml-2" v-model="postData.crmName"/>
                    <div><span style="margin-left: 30px;margin-right: 5px;">所属部门:</span><a-input-search placeholder="全部" style="width: 140px"  v-model="officeNames" read-only @click="() => (officeVisible=true)" @search="() => (officeVisible = true)"/></div>
                    <input-group-search title="业务人员" modalTitle="选择人员" rightStyle="width: 150px;" treeType="officeUser" v-model="postData.userId"/>
                    <form-select title="联系状态" class="ml-2" rightStyle="width:120px;" v-model="postData.touchStatus" v-show="false"
                      :dataList="[
                      { key: 1, title: '已联系' },
                      { key: 0, title: '未联系' }]"/>
                    <nly-button variant="info" @click="getFollowAnalysisLit" button-class="mr-2" style="margin-left: 35px;">查询</nly-button>
                  </nly-col>
                </nly-row>
              </div>
              <a-table
                class="a-base-table"
                :rowSelection="houseTable.rowSelection"
                :columns="columns"
                :pagination="houseTable.pagination"
                :data-source="houseTable.data"
                :scroll="houseTable.scroll"
                :components="components"
                @change="onTableChange"
                bordered
              >
                <a slot="crmName" slot-scope="text, record" @click="goToDetail(record)" class="goToDetail" >{{record.crmName}}</a>
              </a-table>
            </a-tab-pane>
            <a-tab-pane key="2" tab="客户分析">
              <div class="a-button-bar goods">
               <nly-row class="col-12 ml-1 mb-2 lr mt-4">
                  <nly-col xs="12" sm="12" md="12" lg="12" xl="12" class="form-inline" style="justify-content: left;">
                    <form-select title="分析类型"  class="ml-2" rightStyle="width:120px;" v-model="postData.analysisType" @change="changeAnalysisType"
                      :dataList="[
                      { key: 0, title: '按部门分析' },
                      { key: 1, title: '按人员分析' },
                      { key: 2, title: '按区域分析' },
                      { key: 3, title: '按等级分析' },
                      { key: 4, title: '按行业分析' },
                      { key: 5, title: '按规模分析' },
                      { key: 6, title: '按来源分析' }]"/>
                    <div v-show="isOfficeShow"><span style="margin-left: 30px;margin-right: 5px;">所属部门:</span><a-input-search placeholder="全部" style="width: 140px"  v-model="officeNames" read-only @click="() => (officeVisible=true)" @search="() => (officeVisible = true)"/></div>  
                    <form-select title="客户类型"  class="ml-2" rightStyle="width:120px;" v-model="postData.crmType"  addDefaultText="全部"
                      :dataList="[
                      { key: 1, title: '潜在客户' },
                      { key: 2, title: '成交客户' }]"/>
                    <form-rang-date-picker title="创建日期" size="small" rightStyle="min-width: 150px; max-width: calc(410px + 0.25rem);" format="YYYY-MM-DD" v-model="createDate"/>
                    <!-- <input-group-search title="所属人员" modalTitle="选择人员" rightStyle="width: 150px;" treeType="officeUser" v-model="postData.userId"/> -->
                    <nly-button variant="info" @click="getCrmAnalysisTable" button-class="mr-2" style="margin-left: 35px;">查询</nly-button>
                  </nly-col>
                </nly-row>
              </div>
              <div class="echarDiv">
                <v-chart ref="registers_creditChart" :options="options" :auto-resize='true' theme='markPoint' :style="{width:'100%'}" />
              </div>
            </a-tab-pane>
            <a-tab-pane key="3" tab="销售漏斗">
                <salefunnel ></salefunnel>
            </a-tab-pane>
          </a-tabs>
          <ag-modal-form :form="form"></ag-modal-form>
          <a-modal v-model="officeVisible" title="选择部门" centered on-ok="handleok" width="300px">
            <div style="height: 400px; overflow-y: scroll;">
              <a-input-search style="margin-bottom: 8px" v-model="searchOfficeName" placeholder="输入部门名称" @change="onChange" />
              <a-tree
                v-model="checkedOfficeKeys"
                :tree-data="officeTreeData"
                :show-icon="true"
                checkable
                :defaultExpandAll="true"
                @check="officeCheck"
              />
            </div>
            <template slot="footer">
              <a-button key="submit" type="primary" @click="() => (officeVisible = false)">确定</a-button>
              <a-button key="back" @click="() => (officeVisible = false)">关闭</a-button>
            </template>
          </a-modal>
        </div>
      </div>
    </div>
  </nly-content-wrapper>
</template>
<script>
const data = [];
for (let i = 0; i < 12; i++) {
  data.push({
    key: i,
    index: i + 1,
    beginTime: `Edrward ${i}`,
    endTime: 32
  });
}

import table from "@/mixins/table";
import { followAnalysisLit, crmAnalysisTable } from "@/api/crm/statistics";
import { components } from "@/utils/antTableComponents";
import { officeUserListToTree, searchInTreeData } from "@/utils/tree";
import { TreeDataOffice } from "@/api/office";

// import ECharts from 'vue-echarts'
// import "echarts/lib/chart/bar";
// import "echarts/lib/chart/line";
// import "echarts/lib/chart/pie";
// import "echarts/lib/component/tooltip";
// import "echarts/lib/component/legend";
// import "echarts/lib/component/markPoint";
// import "echarts/lib/component/markLine";
// import "echarts/lib/component/graphic";
// import 'echarts/lib/component/title';
// import 'echarts/lib/component/toolbox';

import salefunnel from "@/views/crm/business/salefunnel";      //销售漏斗

export default {
  mixins: [table],
  mounted() {
    this.getFollowAnalysisLit();
    this.getCrmAnalysisTable();
    window.addEventListener("resize", this.resizeTheChart);

    TreeDataOffice({ isLoadUser: 1 }).then(response => {
      const { data } = response;
      const childrenNav = [];
      officeUserListToTree(data, childrenNav, "0");
      this.userAllData = childrenNav;
      this.officeTreeData = childrenNav;
    });
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.resizeTheChart);
  },
  components: {
    'v-chart': VueECharts,
    salefunnel
  },
  data() {
    const columns = [
      { title: "客户名称", dataIndex: "crmName", key: "crmName", width: 120, align: "left",},
      { title: "首次跟进时间", dataIndex: "firstTouchDate", key: "firstTouchDate", width: 120 },
      { title: "最后跟进时间", dataIndex: "lastTouchDate", key: "lastTouchDate", width: 120 },
      { title: "联系次数", dataIndex: "toucheTimes", key: "toucheTimes", width: 120 },
      { title: "未联系天数", dataIndex: "noTouchDays", key: "noTouchDays", width: 120 },
      { title: "所属行业", dataIndex: "industry", key: "industry", width: 120 },
      // { title: "所属人员", width: 120, dataIndex: "collarUserName", key: "collarUserName" },
      { title: "业务人员", width: 120, dataIndex: "salesManName", key: "salesManName" },
      {
        title: "类别", dataIndex: "type", key: "type", width: 120,
        customRender: (text, row) => {
          const type = ["线索客户", "潜在客户", "成交客户"]
          return type[text];
        }
      }
    ];

    //客户分析类型
    const analysisName = ['部门分析', '人员分析', '区域分析', '等级分析', '行业分析', '规模分析', '来源分析'];
    //表格 头部 可伸缩
    this.components = components(columns);

    return {
      tabKey: "1",
      touchDate: [],
      createDate: [],
      analysisName,
      columns,
      postData: {
        current: 1,
        size: 20,
        crmName: "",
        crmType: "",
        officeId: "",
        userId: "",
        touchStatus: null,
        analysisType: 0,
        collarDate: null,
        analysisTypeName: '部门分析对比图'
      },
      form: {
        show: false,
        data: {},
        title: "",
        columns: []
      },
      houseTable: this.tableInit({
        data,
        scroll: { x: 1000 },
        pagination: {
          defaultPageSize: 20,
          current: 1,
          pageSize: 20,
          total: 0,
          showTotal: total => {
            return (
              <div>
                共 {total} 条数据，每页
                <a-input-number
                  value={this.houseTable.pagination.pageSize}
                  min={1}
                  max={500}
                  onPressEnter={e => this.changePageSize(e)}
                />条
              </div>
            );
          },
          showQuickJumper: true,
          showLessItems: true
        }
      }),
      crmAnalysisXData: [], //客户分析X轴数据
      crmAnalysisYData: [], //客户分析Y轴数据
      options: {},
      axisLabel: {},
      officeNames: "",
      officeIds: "",
      officeTreeData: [], //用户搜索数据
      userAllData: [], //用户所有tree数据
      officeVisible: false,
      checkedOfficeKeys: [],
      isOfficeShow: true,
      searchOfficeName: "",
    };
  },
  methods: {
    resizeTheChart() {
      if (this.$refs.registers_creditChart) {
        this.$refs.registers_creditChart.resize();
      }
    },
    createOption() {
      this.options = {
        title: {
          text: this.postData.analysisTypeName,
          left: 50
        },
        legend: {
          data:['客户数量']
        },
        animation : false,
        calculable : false,
        tooltip : {
          showDelay : 5, // 显示延迟，添加显示延迟可以避免频繁切换，单位ms
          axisPointer : {   // 坐标轴指示器，坐标轴触发有效
            type : 'shadow'   // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        toolbox: {
          show : true,
          right: 150,
          feature : {
            dataView : {show: false, readOnly: true},
            magicType : {show: true, type: ['line', 'bar']},
            restore : {show: true},
            saveAsImage : {show: true}
          },
          iconStyle: {borderColor: 'red'},
          emphasis: {
            iconStyle: {
              textPadding: 15
            }}
        },
       grid: { 
		     x:  60,//控制x轴
         y2: 200 // y2可以控制倾斜的文字狱最右边的距离，放置倾斜的文字超过显示区域
		    },
        xAxis: {
          type : 'category',
          data: this.crmAnalysisXData,
          axisLabel: this.axisLabel 
        },
        yAxis: {
          type : 'value'                
        },
        series: [  // 内容数据
          {
            name: "客户数量", // 序列名称
            type: "bar", // 类型
            label: {
              // 图形上的文本标签
              show: true,
              position: "top", // 相对位置
              rotate: 0, // 旋转角度
              color: "red"
            },
            barMaxWidth: 100,
            data: this.crmAnalysisYData
          }
        ]
      }
    },
    //客户统计分析
    getCrmAnalysisTable() {
      if (this.createDate != null && this.createDate.length > 1) {
        this.postData.createBeginDate = this.createDate[1][0];
        this.postData.createEndDate = this.createDate[1][1];
      }
      this.postData.officeIds = this.officeIds;
      crmAnalysisTable(this.postData).then(response => {
        if(response.code == 200) {
          if(response.data != null && response.data.dataName.length > 0) {
            this.crmAnalysisXData = response.data.dataName.split(",");
            this.crmAnalysisYData = response.data.dataCount.split(",");
            if(this.crmAnalysisXData.length < 10) {
              this.axisLabel = {};
            }else {
              this.axisLabel = {
                interval: 0,  
                margin: 10,
                formatter:function(value) {  
                  return value.split("").join("\n");  
                }  
              }
            }
            
          }else {
            this.crmAnalysisXData = [];
            this.crmAnalysisYData = [];
            this.axisLabel = {};
          }
          this.createOption();
        }
      });
    },
    getFollowAnalysisLit() {
      console.log(this.touchDate);
      if (this.touchDate != null && this.touchDate.length > 1) {
        this.postData.touchBeginDate = this.touchDate[1][0];
        this.postData.touchEndDate = this.touchDate[1][1];
      }
      this.postData.officeIds = this.officeIds;
      followAnalysisLit(this.postData).then(response => {
        if (response.code == 200) {
          const { data } = response;
          const { records, total, current, size } = data;
          this.houseTable.data = records;
          Object.assign(this.houseTable.pagination, {
            total
          });
        }
      });
    },
    //客户分析类型切换
    changeAnalysisType(val, info) {
      if(val == 0) {
        this.isOfficeShow = true;
      }else {
        this.isOfficeShow = false;
      }
      this.$set(this.postData,"analysisTypeName", this.analysisName[parseInt(val)] + "对比图");
      this.getCrmAnalysisTable();
      console.log(val);
    },
    //跳转到 客户详情联系记录
    goToDetail(item) {
      const { permissions } = this;
      this.$router.push(`/crm/customer/detail/${item.crmId}/touch`);
    },
    //部门选择
    officeCheck(keys, info) {
      console.log(keys);
      this.checkedOfficeKeys = keys;
      this.officeNames = "";
      this.officeIds = "";
      if (info.checkedNodes.length > 0) {
        for (let i = 0; i < info.checkedNodes.length; i++) {
          const id = info.checkedNodes[i].data.props.id;
          const name = info.checkedNodes[i].data.props.name;
          this.officeNames += name + ",";
          this.officeIds += id + ",";
        }
        this.officeNames = this.officeNames.slice(0, this.officeNames.length - 1);
        this.officeIds = this.officeIds.slice(0, this.officeIds.length - 1);
      }
    },
    //部门搜索
    onChange(e) {
      const value = e.target.value;
      console.log(value);
      if(value) {
        const keys = [];
        const treeData = searchInTreeData(keys, this.userAllData, "title", value);
        this.officeTreeData = treeData;
        this.expandedUserKeys = keys;
      }else {
        this.expandedUserKeys = [];
        this.officeTreeData = this.userAllData;
      }
    },
    changePageSize(e) {
      const value = e.target.value;
      const { pagination } = this;

      console.log(e, value);
      Object.assign(this.postData, {
        "size": value
      });
      Object.assign(this.houseTable.pagination, {
        pageSize: Number.parseInt(value)
      });
      this.getFollowAnalysisLit();
    },
    onTableChange(pagination, filters, sorter) {
      Object.assign(this.postData, {
        "current": pagination.current,
        "size": pagination.pageSize
      });
      Object.assign(this.houseTable.pagination, {
        current: pagination.current,
        pageSize: pagination.pageSize
      });
      this.getFollowAnalysisLit();
    },
    remove() {
      this.houseTable.remove(() => {});
    },
     //tab切换
    tabChange(key) {
      console.log(key);
      this.isOfficeShow = true;
      this.officeIds = "";
      this.officeNames = "",
      this.checkedOfficeKeys = [];
      this.searchOfficeName = "";
    },
  },
 
};
</script>
<style lang="scss" scoped>
::v-deep {
  .ant-tabs,
  .ant-tabs-content,
  .ant-tabs-tabpane {
    display: flex;
    flex-direction: column;
    flex-grow: 1;
    height: 100%;
  }
  .echarts {
    width: 100%;
    height: 100%; 
  }
  .content-wrapper {
    min-height: auto !important;
    height: auto !important;
    flex-grow: 1 !important;
    margin: 0px !important;
    .content-header {
        margin: 0 !important;
        padding: 0 !important;
    }
  }
}
.goods {
  display: flex;
  justify-content: space-between;
}
.view {
  width: calc(100%);
  height: 100%;
  padding: 10px;
}
.echarDiv{
  height: 700px;
  width: calc(100%);
  margin-top: 25px;
  overflow: auto;
}

</style>